package org.letscode.wopiserver.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.letscode.wopiserver.util.FileUtils;
import org.letscode.wopiserver.util.TokenUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title: WOPIController.java
 * @Description: WOPI的接口层
 * @author zhengzhq E-Mail:zzq0324@qq.com
 * @date 2016年11月27日 下午7:06:35
 */
@RestController
public class WOPIController {

  private static Map<String, String> FILE_Map = new HashMap<String, String>();

  static {
    FILE_Map.put("1", "入职员工培训.ppt");
    FILE_Map.put("2", "需求卡片模板.docx");
    FILE_Map.put("3", "业务往来报表.xls");
    FILE_Map.put("4", "[MS-WOPI]-150910.pdf");
  }

  /**
   * 通过文件唯一标识以及token获取文件的详细信息
   * 
   * @param fileId 文件的唯一标识，比如可以是MD5或者数据库的id。此处fileId为对应的文件名
   * @param access_token 访问的token
   * @return
   */
  @ResponseBody
  @RequestMapping(value = "/files/{fileId}", method = RequestMethod.GET)
  public Map<String, String> getFileInfo(@PathVariable("fileId") String fileId,
      @RequestParam("access_token") String token, HttpServletResponse response) {
    boolean isTokenValid = TokenUtil.verifyToken(token);
    if (!isTokenValid) {// 按照wopi协议，返回HTTP CODE=401
      response.setStatus(HttpStatus.UNAUTHORIZED.value());

      return null;
    }

    Map<String, String> fileInfoMap = FileUtils.getFileInfo(FILE_Map.get(fileId));
    if (fileInfoMap == null) {// 根据fileId找不到对应的文件，按照wopi协议返回HTTP CODE=404
      response.setStatus(HttpStatus.NOT_FOUND.value());

      return null;
    }

    return fileInfoMap;
  }

  /**
   * 下载附件内容，与上面的方法在url上的区别为增加了/contents，意为下载该附件下的内容
   * 
   * @param fileId 文件的唯一标识，比如可以是MD5或者数据库的id。此处fileId为对应的文件名
   * @param response
   * @throws Exception
   */
  @RequestMapping(value = "/files/{fileId}/contents")
  public void getFileContent(@PathVariable("fileId") String fileId,
      @RequestParam("access_token") String access_token, HttpServletResponse response)
      throws Exception {
    System.out.println("download file...");
    File file = FileUtils.getFile(FILE_Map.get(fileId));
    if (file == null) {// 根据fileId找不到对应的文件，按照wopi协议返回HTTP CODE=404
      response.setStatus(HttpStatus.NOT_FOUND.value());
    } else {
      response.addHeader("Content-Disposition",
          "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO-8859-1"));
      response.addHeader("Content-Length", String.valueOf(file.length()));

      OutputStream out = null;
      try (InputStream is = new FileInputStream(file)) {
        byte[] buffer = new byte[is.available()];
        is.read(buffer);

        out = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        out.write(buffer);
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (out != null) {
          out.flush();
          out.close();
        }
      }
    }
  }
}
